package view

import (
	"blog/app/models/category"
	"blog/app/models/user"
	"blog/pkg/auth"
	"blog/pkg/flash"
	"blog/pkg/logger"
	"blog/pkg/route"
	"embed"
	"html/template"
	"io"
	"io/fs"
	"strings"
)

type D map[string]interface{}

var TplFS embed.FS

//Render 渲染通用的视图
func Render(w io.Writer, data D, tplFiles ...string) {
	RenderTemplate(w, "app", data, tplFiles...)
}

//RenderSimple渲染简单的视图
func RenderSimple(w io.Writer, data D, tplFiles ...string) {
	RenderTemplate(w, "simple", data, tplFiles...)
}

//RenderTemplate 渲染视图
func RenderTemplate(w io.Writer, name string, data D, tplFiles ...string) {

	data["isLogined"] = auth.Check()
	data["flash"] = flash.All()
	data["Users"], _ = user.All()
	data["loginUser"] = auth.User()
	data["Categories"], _ = category.All()

	allFiles := getTemplateFiles(tplFiles...)
	//解析所有模板文件
	tmpl, err := template.New("").
		Funcs(template.FuncMap{
			"RouteName2URL": route.Name2URL,
		}).ParseFS(TplFS, allFiles...)

	logger.LogError(err)
	//渲染模板
	err = tmpl.ExecuteTemplate(w, name, data)
	logger.LogError(err)
}

func getTemplateFiles(tplFiles ...string) []string {
	//设置模板相对路径
	viewDir := "resources/views/"

	//便利文件列表Slice,设置正确的路径,支持dir.filename语法糖
	for i, f := range tplFiles {
		tplFiles[i] = viewDir + strings.Replace(f, ".", "/", -1) + ".gohtml"
	}

	//获取所有布局模板文件Slice
	layoutFiles, err := fs.Glob(TplFS, viewDir+"layouts/*.gohtml")

	logger.LogError(err)
	//合并所有文件
	return append(layoutFiles, tplFiles...)
}
